package com.tianheng.wanzhou.datacollecting.util;

import java.nio.ByteBuffer;

public class StrUtil {
    //16位
    public static Integer reverseHexStr2Int(String hex) {
        String low = hex.substring(0, 2);
        String high = hex.substring(2);
        String newHex = high + low;
        return hexStr2Int(newHex);
    }
    //32位
    public static Long reverseHex2Int(String hex) {
        String low = hex.substring(0, 4);
        String high = hex.substring(4);
        String newHex = high + low;
        return hexStr2Long(newHex);
    }

    public static String hexStr2BinaryStr(String hex) {
        int length = hex.length();
        char[] chars = hex.toCharArray();
        StringBuilder stringBuilder = new StringBuilder();
        for (char c : chars) {
            String x = Integer.toBinaryString(c);
            while (x.length() < 4){
                x = "0" + x;
            }
            stringBuilder.append(x);
        }
        return stringBuilder.toString();
    }

    public static String hexStr2version(String hex) {
        Integer intPart = Integer.parseInt(hex.substring(0, 2), 16);
        Integer decimal = Integer.parseInt(hex.substring(2, 4), 16);
        StringBuilder stringBuilder = new StringBuilder().append(intPart).append(".").append(decimal);
        return stringBuilder.toString();
    }

    public static Integer hexStr2Int(String hex) {
        return Integer.valueOf(hex, 16);
    }

    public static String hexStr2IntStr(String hex) {
        return Integer.valueOf(hex, 16).toString();
    }

    public static Long hexStr2Long(String hex) {
        return Long.valueOf(hex, 16);
    }

    public static String hexStr2LongStr(String hex) {
        return Long.valueOf(hex, 16).toString();
    }

    public static byte[] hexStr2Byte(String hex) {
        ByteBuffer bf = ByteBuffer.allocate(hex.length() / 2);
        for (int i = 0; i < hex.length(); i++) {
            String hexStr = hex.charAt(i) + "";
            i++;
            hexStr += hex.charAt(i);//charAt取出在hex中下标索引为i的字符
            byte b = (byte) Integer.parseInt(hexStr, 16);//把16进制的hexStr转10进制
            bf.put(b);
        }
        return bf.array();
    }
    /**
     * 16进制（字符串格式）转2进制;按位解析 高4位和低4位反一反 08 解析为1000 0000
     * @param str
     * @return byte[]
     */
    public static byte[] convertStrHexToBit(String str){

        char[] chars = str.toCharArray();
        int len=str.length();
        byte[] bit = new byte[len*4];
        byte[] hexByte=hexStr2Byte(str);//字符串转为byte
        for (int j = 0; j < hexByte.length; j++) {

            for (int i = 3; i >= 0; i--) {
                bit[i+8*j] = (byte)(hexByte[j] & 1);
                hexByte[j] = (byte) (hexByte[j] >> 1);
            }
            for (int i = 7; i >= 4; i--) {
                bit[i+8*j] = (byte)(hexByte[j] & 1);
                hexByte[j] = (byte) (hexByte[j] >> 1);
            }
        }
        return bit;
    }

    /**
     * 字符串转16进制
     * @param str
     * @return String
     */
    public static String convertStringToHex(String str){

        char[] chars = str.toCharArray();

        StringBuffer hex = new StringBuffer();
        for(int i = 0; i < chars.length; i++){
            hex.append(Integer.toHexString((int)chars[i]));
        }

        return hex.toString();
    }

    /**
     * 16进制转ASCII字符串
     * @param hex
     * @return String
     */
    public static String convertHexToString(String hex){

        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();

        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for( int i=0; i<hex.length()-1; i+=2 ){

            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char)decimal);

            temp.append(decimal);
        }

        return sb.toString();
    }

    /**
     * 16进制转ASCII字符串
     * @param hex
     * @return String
     */
    public static String convertHexToASCII(String hex){

        StringBuilder sb = new StringBuilder();
       // StringBuilder temp = new StringBuilder();

        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for( int i=0; i<hex.length()-1; i+=4 ){

            //grab the hex in pairs
            String output = hex.substring(i, (i + 4));
            if(output!="0000")
            {
                //convert hex to decimal
                int decimal = Integer.parseInt(output, 16);
                //convert the decimal to character
                sb.append((char)decimal);
            }


         //   temp.append(decimal);
        }

        return sb.toString();
    }

    /**
     *
     * @param
     * @return String
     */
    public static String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2){
                sb.append(0);
            }

            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }
    /**
     *
     * @param
     * @return String
     */
    public static String toHexString1(byte[] b) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < b.length; ++i) {
            buffer.append(toHexString1(b[i]));
        }
        return buffer.toString();
    }


    /**
     *
     * @param
     * @return String
     */
    public static String toHexString1(byte b) {
        String s = Integer.toHexString(b & 0xFF);
        if (s.length() == 1) {
            return "0" + s;
        } else {
            return s;
        }
    }
    /**
     * 和校验
     * @param messageNullCheck，check
     * @return boolean
     */
    public static boolean sumCheck(String messageNullCheck, String check) {
        boolean result = false;

        int checkNum = 0;
        for(int i=0;i<messageNullCheck.length()/2;i++){
            String hex = messageNullCheck.substring(i*2,i*2+2);
            checkNum=checkNum+Integer.parseInt(hex, 16);
        }
        if(checkNum==Integer.parseInt(check, 16)){
            result =true;
        }
        return result;
    }


    /**
     * 获取当前执行路径
     * @return String
     */
    public static String getAppAddress(){
        return System.getProperty("user.dir");
    }


    /**
     * 将字符串如： [3,2,1]，截成数组输出
     * @return String[]
     */
    public static String[] getArrayStrReturnArray(String arrayStr){
        return arrayStr.substring(1,arrayStr.length()-1).split(",");
    }

    /**
     * 将字符串如： [3,2,1]，截成数组输出
     * @return int[]
     */
    public static int[] getArrayStrReturnIntArray(String arrayStr){
        if(arrayStr.indexOf("\"")!=-1||arrayStr.indexOf("[")==-1){
            //过滤不正确传过来的内容
            int[] result=new int[1];
            result[0]=0;
            return result;
        }
        String[] array=arrayStr.substring(1,arrayStr.length()-1).split(",");
        int[] result=new int[array.length];
        for (int i = 0; i < array.length; i++) {
            try {
                result[i] = Integer.parseInt(array[i]);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
            return result;
    }

    /**
     * 将字符串如： [3,2,1]，截成  3,2,1
     * @return String
     */
    public static String getArrayStrReturnSearchInStr(String arrayStr){
        return arrayStr.substring(1,arrayStr.length()-1);
    }

    /**
     * 将String[]如： [3,2,1]，返回成字符串“3,2,1”
     * @return String
     */
    public static String getIntArrayReturnString(String[] intArray){
        String result;
        StringBuilder resultBuilder=new StringBuilder();
        for (int i = 0; i < intArray.length; i++) {
            resultBuilder.append(String.valueOf(intArray[i])).append(",");
        }
        result=resultBuilder.toString();
        if(result.length()>0){
            result=result.substring(0,result.length()-1);
        }
        return result;
    }


    /**
     * 截取设备编号
     * @return int
     */
    public static int getMachineIdFormHead(String msg){
        String strMacId=msg.substring(22,30);
        int machineId=Integer.parseInt(strMacId,16);
        return machineId;
    }

    /**
     * 截取企业编号
     * @return int
     */
    public static int getCompanyIdFormHead(String msg){

        int companyId=0;
        int temp=Integer.parseInt(msg.substring(12,16),16);
        if(temp==28) {

            companyId = 10000007;//木兰
        }
        else{
            companyId=10000000+temp;//
        }


        return companyId;
    }

    /**
     * 截取车间编号
     * @return int
     */
    public static int getWorkshopIdFormHead(String msg){
        int workshopId=Integer.parseInt(msg.substring(16,20),16);
        return workshopId;
    }
    /**
     *  获取数据长度
     */
    public static int getDataLength(byte[] buffer,int startIndex){

        int temp0=(buffer[startIndex]&0xff) << 24;
        int temp1=(buffer[startIndex+1]&0xff) << 16;
        int temp2=(buffer[startIndex+2]&0xff) << 8;
        int temp3=buffer[startIndex+3]&0xff;
        int length=temp0+temp1+temp2+temp3;

        return length;
    }
    public static String expandStringToHeadOrFoot(String str,int length,String charStr,boolean isHead){
        StringBuilder tmp =new StringBuilder();
        for(int i=0;i<Math.abs(str.length()-length);i++){
            tmp.append(charStr);
        }
        if(isHead){
            str = tmp.toString()+str;
        }else{
            str = str+tmp.toString();
        }
        return str;
    }


    public static Data getStatus(String msg, int endIndex) {
        long dec = Long.valueOf(msg, 16);
        String bin = Long.toBinaryString(dec);
        while (bin.length() < 32) {
            bin = "0" + bin;
        }
        String result = bin.substring(endIndex, endIndex + 1);
        return new Data(result);

    }

}
